import { createStore } from 'vuex'
import { generateMixed, storageAdd, storageGet } from '../utils/common'
import { findIndex } from 'lodash'

// 初始化列表，激活每日待办
let todoList = storageGet('todoList') || []
let doneList = storageGet('doneList') || []
let last = localStorage.getItem('lastOriginTime')
const itemOriginHandle = o => {
  const stopDate = new Date(o.stopTime)
  return new Date().setHours(0,0,0,0) + (stopDate.getTime() - stopDate.setHours(0,0,0,0))
}
const originHandle = () => {
  for (let o of todoList) {
    if (o.daily) {
      o.stopTime = itemOriginHandle(o)
    }
  }
  for (let i = 0; i < doneList.length; i++) {
    if (doneList[i].daily) {
      doneList[i].stopTime = doneList[i].stopTime = itemOriginHandle(doneList[i])
      todoList.unshift(doneList[i])
      doneList[i] = null
    }
  }
  doneList = doneList.filter(o => o)
  localStorage.setItem('todoList', JSON.stringify(todoList))
  localStorage.setItem('doneList', JSON.stringify(doneList))
  localStorage.setItem('lastOriginTime', new Date().getTime())
  console.log('Todo list is initialized!\n待办事项已初始化完毕！')
}
if (!last){
  originHandle()
} else {
  // 最后初始化时间，一天只初始化一次
  last = new Date(parseInt(last))
  let now = new Date()
  const isYesterday = now.getDate() != last.getDate() || now.getMonth() != last.getMonth()
  if ((todoList.length > 0 || doneList.length > 0) && isYesterday) {
    originHandle()
  }
}


export default createStore({
  state () {
    return {
      todoList,
      doneList,
      mapStatus: ['普通', '重要', '紧急', '非常紧急'],
    }
  },
  mutations: {
    pushTodoItem(state, item){
      if (!item.key) {
        const createTime = new Date().getTime()
        item = {
          ...item,
          createTime,
          key: generateMixed(),
          daily: false,
          status: 0
        }
      }
      state.todoList.unshift(item)
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    },
    removeTodoItem(state, item){
      const index = findIndex(state.todoList, item)
      state.todoList.splice(index, 1)
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    },
    editTodoItem(state, item){
      const index = findIndex(state.todoList, {key: item.key, createTime: item.createTime})
      state.todoList[index] = item
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    },
    pushDoneItem(state, item){
      state.doneList.push(item)
      storageAdd('doneList', item)
    },
    removeDoneItem(state, index){
      state.doneList.splice(index, 1)
      localStorage.setItem('doneList', JSON.stringify(state.doneList))
    },
    clearDoneList(state){
      state.doneList = []
      localStorage.removeItem('doneList')
    }
  }
})